﻿using LdtCommonFreeSql;
using LdtCommonUtil;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NlpApp.Model;
using NlpApp.Model.RexUninlu;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NlpApp.Bll.Personalize
{
    /// <summary>
    /// 询问笔录提取业务类（事实时间轴）
    /// </summary>
    public class WS010000190
    {
        private readonly ServiceBll serviceBll;
        private readonly IFreeSql freeSql;
        public WS010000190(ServiceBll serviceBll, FreesqlDb freesqlDb)
        {
            this.serviceBll = serviceBll;
            freeSql = freesqlDb.GetFreeSql("localcache", new ConnConfig
            {
                Dbcode = Path.Combine(AppContext.BaseDirectory, "localdb"),
                Dbtype = FreeSql.DataType.Sqlite,
            });
        }
        /// <summary>
        ///创建并保存事实时间轴数据
        /// </summary>
        /// <param name="id">The identifier.唯一标识</param>
        /// <param name="content">The content.文本内容</param>
        /// <returns></returns>
        public async Task<HttpReturnEntity> CreateDateData(string id, string content)
        {
            bool iStart = false;
            List<RexUninluInfolistItemResult> results = new List<RexUninluInfolistItemResult>();
            //先拆行，返回事件轴的时间，行号，增加询问时间的返回,组合起来
            var datas = content.Split("\r".ToArray());
            //先取询问笔录的时间，取到后就不要再取了
            NlpExtractModel extractModel = new NlpExtractModel()
            {
                Schemas = new List<string> { "日期" }
            };
            for (int i = 0; i < datas.Length; i++)
            {
                var data = datas[i].Trim();
                if (results.Any() && !iStart)
                {
                    if ((data.StartsWith('问') || data.StartsWith('答')))
                    {
                        iStart = true;
                    }
                    else
                    {
                        continue;
                    }
                }
                var sens = data.Split("。,，？?！!;；".ToArray()).Where(p => !string.IsNullOrEmpty(p.Trim())).ToArray();
                if (sens.Length > 0)
                {
                    extractModel.Texts = sens;
                    var uieresults = await serviceBll.GetUieByUrl(extractModel);
                    var r1 = uieresults.SelectMany(item => serviceBll.ConvertDicToRex(item, i).ToList()).ToList();
                    if (r1.Any())
                    {
                        ///取到的第一个时间是笔录时间，并且问答开始
                        if (!results.Any())
                        {
                            r1[0].code = "笔录时间";
                            results.Add(r1[0]);
                            extractModel.Schemas = new List<string> { "事件时间" };
                        }
                        else
                        {
                            results.AddRange(r1.Select(p =>
                            {
                                p.sourcecontent = data;
                                p.code = p.name; return p;
                            }));
                        }
                    }
                }
            }
            LocalCacheModel model = new LocalCacheModel
            {
                id = id,
                content = content,
                result = JsonConvert.SerializeObject(results)
            };
            freeSql.InsertOrUpdate<LocalCacheModel>().AsTable("ws010000190dateresult").SetSource(model).ExecuteAffrows();
            return new HttpReturnEntity { Code = "0", Message = "成功" };
        }
        /// <summary>
        /// Gets the date data.获取结果
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <returns></returns>
        public async Task<object> GetDateData(string id)
        {
            var r1 = await freeSql.Ado.QuerySingleAsync<LocalCacheModel>($"select result from ws010000190dateresult where id='{id}'");
            if (r1 == null)
            {
                throw new ServiceException("不存在对应的识别结果");
            }
            return new JRaw(r1.result);
        }
    }
}
